package com.blog.config.realm;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.blog.common.base.ResponseReslut;
import com.blog.common.constants.Constants;
import com.blog.entity.sys.Menu;
import com.blog.entity.sys.Role;
import com.blog.entity.sys.User;
import com.blog.service.sys.MenuService;
import com.blog.service.sys.RoleService;
import com.blog.service.sys.UserService;


/**
 * 
 * @ClassName: ShiroRealm
 * @author: chb
 * @date: 2018年7月6日 下午8:04:05
 * @作用：自定义realm
 */
public class ShiroRealm extends AuthorizingRealm{
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private RoleService roleService;
	
	@Autowired
	private MenuService menuService;
	
 
	 /**
     * 权限认证，为当前登录的Subject授予角色和权限（角色的权限信息集合）
     * @RequiresPermissions(value="用户管理")这个注解 会进入  这个方法
     */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
		
		//得到用户名
		String userName=(String) SecurityUtils.getSubject().getPrincipal();
		SimpleAuthorizationInfo  info=new  SimpleAuthorizationInfo();
		ResponseReslut rt=userService.findByUserName(userName);
		User user=(User) rt.getData();
		//查询用户角色
		List<Role> roleList=roleService.listRole(user.getId());
		//HashSet实现了Set接口，它不允许集合中出现重复元素
		Set<String> roles=new HashSet<String>();
		for(Role role : roleList)
		{
			roles.add(role.getName());
			//根据角色id查询用户的权限
			List<Menu> menuList=menuService.listMenu(role.getId());
			
			for(Menu menu : menuList)
			{
				//把权限放到 shiro里面去
				info.addStringPermission(menu.getName());
			}
		}
		info.setRoles(roles);//添加角色
		
		return info;
	}
	  /**
     * 提供账户信息返回认证信息（ 用户登陆判断）
     */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		 
		//1.通过用户名 查找用户的对象
		String userName=(String) token.getPrincipal();
		ResponseReslut rt=userService.findByUserName(userName);
	
		if(Constants.HTTP_RES_CODE_200.equals(rt.getCode()))
		{	
			 User user=(User) rt.getData();
			//AuthenticationInfo接口实现
			AuthenticationInfo atcf=new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(),"chb");
			return atcf;
		}
		return null;
	}

}
